from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.customer.users import users_controller
from app.controllers.saas.buckling import buckling_controller
from app.controllers.saas.cases import cases_controller
from app.models import Goods, GoodsSku
from app.schemas.base import Success, SuccessExtra,Fail
from app.core.dependency import DependCustomerAuth
from app.schemas.saas import  CasesCreate
from app.core.ctx import CTX_USER_ID

mini_saas_buckling_router = APIRouter()

@mini_saas_buckling_router.get("/list_buckling", summary=f"用户疗程项目", dependencies=[DependCustomerAuth])
async def list_buckling(
        page: int = Query(1, description="页码"),
        page_size: int = Query(1000, description="每页数量"),
        user_id: int = Query(None, description="用户"),
        name: str = Query('', description="商品名称"),
):
    q = Q(user_id=user_id,last_nums__gt=0)
    search_goods_ids = []
    if name:
        search_goods = await Goods.filter(name__contains=name).values("id")
        search_goods_ids = {good['id'] for good in search_goods}  # 获取所有的 goods_id
        q &= Q(goods_id__in=search_goods_ids)
    total, data = await buckling_controller.do_list(page=page, page_size=page_size, search=q)
    goods_ids = {goods['goods_id'] for goods in data}  # 获取所有的 goods_id
    sku_ids = {sku['sku_id'] for sku in data}  # 获取所有的 goods_id
    goods = await Goods.filter(id__in=goods_ids)
    goods_dict = {good.id: good.name for good in goods}
    goods_dict_cover = {good.id: good.cover for good in goods}
    skus = await GoodsSku.filter(id__in=sku_ids)
    skus_dict = {sku.id: sku.sku_name for sku in skus}
    for item in data:
        item['goods_name'] = goods_dict.get(item['goods_id'], "已删除商品")
        item['goods_cover'] = goods_dict_cover.get(item['goods_id'], "")
        item['sku_name'] = skus_dict.get(item['sku_id'], "已删除规格")
        item['select_nums'] = 0
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@mini_saas_buckling_router.post("/create", summary=f"创建划扣", dependencies=[DependCustomerAuth])
async def do_create(
        data_in: CasesCreate,
):
    add_uid = CTX_USER_ID.get()
    user_obj = await users_controller.get(id=add_uid)
    data_in.add_uid = user_obj.id
    data_in.user_id = add_uid

    ret = await cases_controller.do_create(obj_in=data_in)
    if ret:
        return Success(msg="创建成功")
    else:
        return Fail(msg="不足划扣,请检查或者刷新")